export default class BoardCanvas {
    constructor(container) {
        // 容器
        this.container = container
        // canvas画布
        this.canvas = this.createCanvas(container)
        // 绘制工具
        this.ctx = this.canvas.getContext('2d')
        // 起始点位置
        this.startX = 0
        this.stateY = 0
        // 画布历史栈
        this.pathSegmentHistory = []
        this.index = 0

        // 鼠标状态
        this.mouseState = 'brush'

        //  画笔颜色
        this.brushColor = 'black'

        // 画笔宽度
        this.brushWidth= 2

        this.pen= require("src/assets/pen.png")
        this.markerPen=require("src/assets/marker-pen.png")
        this.linearRubber= require("src/assets/linear-rubber.png")

        // 初始化
        this.init()



    }

    // 创建画布
    createCanvas(container) {
        const canvas = document.createElement('canvas')
        canvas.width = container.clientWidth
        canvas.height = container.clientHeight
        canvas.style.display = 'block'
        canvas.style.backgroundColor = 'white'
        container.appendChild(canvas)
        return canvas
    }

    // 初始化
    init() {
        this.addPathSegment()
        this.initContext2DStyle()
        //下面两行，原文件是没有的，如果没有会导致保存的图片没有背景，只有绘画轨迹
        this.ctx.fillStyle = "#ffffff";
        this.ctx.strokeStyle = this.brushColor
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
        this.canvas.addEventListener('contextmenu', e => e.preventDefault())
        this.canvas.addEventListener('mousedown', this.mousedownEvent.bind(this))
        window.document.addEventListener('keydown', this.keydownEvent.bind(this))
    }
    // 设置画笔颜色
    setContextColor(color) {
        this.brushColor = color
        this.mouseState = 'brush'
        this.ctx.save();
        this.ctx.strokeStyle = color
        this.ctx.lineCap = 'round'
        this.ctx.lineJoin = 'round'


    }
    // 设置画笔样式
    initContext2DStyle() {

        this.ctx.save();
        this.mouseState = 'brush'
        this.ctx.strokeStyle = this.brushColor;
        this.ctx.lineWidth = this.brushWidth
        this.ctx.lineCap = 'round'
        this.ctx.lineJoin = 'round'
        this.canvas.style.cursor = `url(${this.pen}),auto`; // 这里示例了将鼠标样式更改为手型指针（pointer）

    }

    contextFine(){
        this.ctx.save();
        this.mouseState = 'brush'
        this.brushWidth = 2
        this.ctx.strokeStyle = this.brushColor;
        this.ctx.lineWidth = this.brushWidth
        this.ctx.lineCap = 'round'
        this.ctx.lineJoin = 'round'
        this.canvas.style.cursor = `url(${this.pen}),auto`; // 这里示例了将鼠标样式更改为手型指针（pointer）
    }

    contextBulky(){
        this.ctx.save();
        this.mouseState = 'brush'
        this.brushWidth = 4
        this.ctx.strokeStyle = this.brushColor;
        this.ctx.lineWidth = this.brushWidth
        this.ctx.lineCap = 'round'
        this.ctx.lineJoin = 'round'
        this.canvas.style.cursor =  `url(${this.markerPen}),auto`; // 这里示例了将鼠标样式更改为手型指针（pointer）
    }

    // 鼠标事件
    mousedownEvent(e) {
        const that = this
        const ctx = this.ctx
        ctx.beginPath()
        ctx.moveTo(e.offsetX, e.offsetY)
        ctx.stroke()

        this.canvas.onmousemove = function (e) {
            // console.log(e.offsetX, e.offsetY)
            if (that.mouseState == 'rubber') {
                //设置圆形，用来作为刮刮乐的下笔形状
                ctx.strokeStyle = "#ffffff"
                ctx.beginPath();
                ctx.arc(e.offsetX, e.offsetY, 20, 0, Math.PI * 2, false);
                ctx.fill()
                ctx.closePath();
                ctx.stroke();

            }

            ctx.lineTo(e.offsetX, e.offsetY)
            ctx.stroke()
        }
        this.canvas.onmouseup = this.canvas.onmouseout = function () {
            that.addPathSegment()
            this.onmousemove = null
            this.onmouseup = null
            this.onmouseout = null
        }
    }

    // 键盘事件
    keydownEvent(e) {
        if (!e.ctrlKey) return
        switch (e.keyCode) {
            case 90:
                this.undo()
                break
            case 89:
                this.redo()
                break
        }
    }

    // 添加路径片段
    addPathSegment() {
        const data = this.ctx.getImageData(0, 0, this.canvas.width, this.canvas.height)
        // 删除当前索引后的路径片段，然后追加一个新的路径片段，更新索引
        this.pathSegmentHistory.splice(this.index + 1)
        this.pathSegmentHistory.push(data)
        this.index = this.pathSegmentHistory.length - 1
    }

    // 撤销
    undo() {
        if (this.index <= 0) return
        this.index--
        this.ctx.putImageData(this.pathSegmentHistory[this.index], 0, 0)
    }
    // 恢复
    redo() {
        if (this.index >= this.pathSegmentHistory.length - 1) return
        this.index++
        this.ctx.putImageData(this.pathSegmentHistory[this.index], 0, 0)
    }
    //获取画布内容
    getImage() {
        return this.canvas.toDataURL();
    }
    //清空画板
    cleanboard() {
        this.ctx.fillStyle = "#ffffff";
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
    }
    // 回显画布
    echoImage(dataImage) {
        let _this = this
        // 创建一个 Image 对象
        var img = new Image(dataImage);
        // 指定 base64 格式的图片作为 Image 对象的 src
        img.crossOrigin = '';
        img.src = dataImage;
        // 等待图片加载完成
        img.onload = function () {
            // 将图片绘制到 Canvas 上
            _this.ctx.drawImage(img, 0, 0);

        }
    }
    //下载图片
    downloadImage() {
        const timestamp = (new Date()).valueOf();
        const dlLink = document.createElement('a');
        dlLink.download = timestamp;
        dlLink.href = this.canvas.toDataURL();
        dlLink.click();
    }
    //橡皮擦
    rubber() {
        this.ctx.save();
        this.mouseState = 'rubber'
        this.canvas.style.cursor = `url(${this.linearRubber}),auto`;
    }

}